
#include "user.h"
#include "serial.h"

void system_init(void)
{
	led(OFF);
	serial_init();       /// 初始化串口资源
	
	serial_write(SERIAL_ID_1, "COM01\r\n", strlen("COM01\r\n"));
}

void app(void)
{
	led_task();
	
	serial_process_callback();
}

void led_task(void)
{
	static uint32_t led_callback_time_ms = 0;
	static GPIO_PinState sta = OFF; 
	
	if( HAL_GetTick()-led_callback_time_ms>=1000 )
	{
		if( sta==OFF ) sta = ON;
		else sta = OFF;
		
		led(sta);
		led_callback_time_ms = HAL_GetTick();
	}
}

void serial_process_callback(void)
{
	static uint32_t serial_callback_time_ms = 0;
	static uint8_t rx_buff[256];
	
	if( HAL_GetTick()-serial_callback_time_ms>=5 )
	{
		uint8_t i = 0;
		uint32_t rx_len = 0;
		for( ; i<USART_MAX_NUM; ++i )
		{
			if( serials[i]!=NULL )
			{
				SERIAL_ID id = serials[i]->id;
				switch(id)
				{
					case SERIAL_ID_1:
						rx_len = serial_read(SERIAL_ID_1, rx_buff, 256);
						if( rx_len>0 )
						{
							serial_write(SERIAL_ID_3, rx_buff, rx_len);
							serial_write(SERIAL_ID_2, rx_buff, rx_len);
						}
						break;
					case SERIAL_ID_2:
						rx_len = serial_read(SERIAL_ID_2, rx_buff, 256);
						if( rx_len>0 )
						{
							serial_write(SERIAL_ID_1, rx_buff, rx_len);
						}
						break;
					case SERIAL_ID_3:
						rx_len = serial_read(SERIAL_ID_3, rx_buff, 256);
						if( rx_len>0 )
						{
							serial_write(SERIAL_ID_1, rx_buff, rx_len);
						}
						break;
					case SERIAL_ID_USB:
						rx_len = serial_read(SERIAL_ID_USB, rx_buff, 256);
						if( rx_len>0 )
						{
							serial_write(SERIAL_ID_1, rx_buff, rx_len);
						}
						break;
					default:
						break;
				}	
				
				open_usart_send(serials[i]);			
			}
		}		
		serial_callback_time_ms = HAL_GetTick();
	}
}
